<!--
  智慧社区移动端 - 充电记录
  @author Wu.Liang
  @date 2024-01-01
-->
<template>
  <view class="charging-record-container">
    <!-- 顶部统计 -->
    <view class="statistics-section">
      <view class="statistics-card">
        <view class="stat-item">
          <text class="stat-value">{{ statistics.totalCount || 0 }}</text>
          <text class="stat-label">总充电次数</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ statistics.totalAmount || 0 }}</text>
          <text class="stat-label">总充电金额</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ statistics.totalPower || 0 }}</text>
          <text class="stat-label">总充电量(kWh)</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ statistics.avgDuration || 0 }}</text>
          <text class="stat-label">平均时长(小时)</text>
        </view>
      </view>
    </view>

    <!-- 筛选条件 -->
    <view class="filter-section">
      <view class="filter-tabs">
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'all' }"
          @click="switchTab('all')"
        >
          全部
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'charging' }"
          @click="switchTab('charging')"
        >
          充电中
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'completed' }"
          @click="switchTab('completed')"
        >
          已完成
        </view>
      </view>
      
      <view class="filter-actions">
        <view class="filter-btn" @click="showDateFilter = true">
          <uni-icons type="calendar" size="16" color="#666"></uni-icons>
          <text>{{ dateRangeText }}</text>
        </view>
        <view class="filter-btn" @click="handleSort">
          <uni-icons type="sort" size="16" color="#666"></uni-icons>
          <text>{{ sortText }}</text>
        </view>
      </view>
    </view>

    <!-- 充电记录列表 -->
    <view class="record-list">
      <view 
        class="record-item" 
        v-for="item in recordList" 
        :key="item.id"
        @click="handleItemClick(item)"
      >
        <view class="record-header">
          <view class="pile-info">
            <text class="pile-no">{{ item.pileNo }}</text>
            <text class="pile-type">{{ item.pileTypeName }}</text>
          </view>
          <view class="status-tag" :class="getStatusClass(item.status)">
            {{ item.statusName }}
          </view>
        </view>
        
        <view class="record-content">
          <view class="info-row">
            <text class="label">车牌号:</text>
            <text class="value">{{ item.licensePlate }}</text>
          </view>
          <view class="info-row">
            <text class="label">开始时间:</text>
            <text class="value">{{ formatTime(item.startTime) }}</text>
          </view>
          <view class="info-row" v-if="item.endTime">
            <text class="label">结束时间:</text>
            <text class="value">{{ formatTime(item.endTime) }}</text>
          </view>
          <view class="info-row" v-if="item.duration">
            <text class="label">充电时长:</text>
            <text class="value">{{ formatDuration(item.duration) }}</text>
          </view>
          <view class="info-row">
            <text class="label">充电电量:</text>
            <text class="value">{{ item.chargedPower || 0 }}kWh</text>
          </view>
          <view class="info-row">
            <text class="label">充电费用:</text>
            <text class="value price">¥{{ item.chargedAmount || 0 }}</text>
          </view>
        </view>
        
        <view class="record-footer">
          <view class="actions">
            <button 
              class="action-btn primary" 
              v-if="item.status === 1"
              @click.stop="handleStopCharging(item)"
            >
              停止充电
            </button>
            <button 
              class="action-btn info" 
              v-if="item.status === 2 && item.paymentStatus === 0"
              @click.stop="handlePayment(item)"
            >
              立即支付
            </button>
            <button 
              class="action-btn default" 
              @click.stop="handleDetail(item)"
            >
              查看详情
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 日期筛选弹窗 -->
    <uni-popup ref="datePopup" type="bottom">
      <view class="popup-content">
        <view class="popup-header">
          <text>选择时间范围</text>
          <uni-icons type="close" size="20" @click="showDateFilter = false"></uni-icons>
        </view>
        <view class="popup-body">
          <view class="date-presets">
            <view 
              class="preset-item" 
              v-for="preset in datePresets" 
              :key="preset.value"
              @click="selectDatePreset(preset)"
            >
              <text>{{ preset.label }}</text>
            </view>
          </view>
          <view class="custom-date">
            <view class="date-input">
              <text class="label">开始日期</text>
              <picker 
                mode="date" 
                :value="customStartDate" 
                @change="onStartDateChange"
              >
                <view class="picker">{{ customStartDate || '请选择' }}</view>
              </picker>
            </view>
            <view class="date-input">
              <text class="label">结束日期</text>
              <picker 
                mode="date" 
                :value="customEndDate" 
                @change="onEndDateChange"
              >
                <view class="picker">{{ customEndDate || '请选择' }}</view>
              </picker>
            </view>
          </view>
          <view class="popup-actions">
            <button class="btn cancel" @click="showDateFilter = false">取消</button>
            <button class="btn confirm" @click="confirmDateFilter">确定</button>
          </view>
        </view>
      </view>
    </uni-popup>

    <!-- 支付弹窗 -->
    <uni-popup ref="paymentPopup" type="center">
      <view class="payment-popup">
        <view class="popup-title">支付确认</view>
        <view class="payment-info">
          <view class="payment-item">
            <text class="label">充电桩:</text>
            <text class="value">{{ currentRecord.pileNo }}</text>
          </view>
          <view class="payment-item">
            <text class="label">车牌号:</text>
            <text class="value">{{ currentRecord.licensePlate }}</text>
          </view>
          <view class="payment-item">
            <text class="label">充电时长:</text>
            <text class="value">{{ formatDuration(currentRecord.duration) }}</text>
          </view>
          <view class="payment-item">
            <text class="label">充电电量:</text>
            <text class="value">{{ currentRecord.chargedPower }}kWh</text>
          </view>
          <view class="payment-item total">
            <text class="label">支付金额:</text>
            <text class="value price">¥{{ currentRecord.chargedAmount }}</text>
          </view>
        </view>
        <view class="payment-methods">
          <view class="method-title">选择支付方式</view>
          <view 
            class="method-item" 
            v-for="method in paymentMethods" 
            :key="method.value"
            @click="selectPaymentMethod(method)"
          >
            <view class="method-info">
              <uni-icons :type="method.icon" size="20" color="#007aff"></uni-icons>
              <text>{{ method.label }}</text>
            </view>
            <uni-icons 
              v-if="selectedPaymentMethod === method.value" 
              type="checkmarkempty" 
              size="20" 
              color="#007aff"
            ></uni-icons>
          </view>
        </view>
        <view class="popup-actions">
          <button class="btn cancel" @click="showPaymentPopup = false">取消</button>
          <button class="btn confirm" @click="confirmPayment">确认支付</button>
        </view>
      </view>
    </uni-popup>

    <!-- 加载更多 -->
    <uni-load-more :status="loadMoreStatus"></uni-load-more>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'

// 响应式数据
const activeTab = ref('all')
const showDateFilter = ref(false)
const showPaymentPopup = ref(false)
const loadMoreStatus = ref('more')

// 筛选数据
const sortType = ref('time') // time, amount, power
const customStartDate = ref('')
const customEndDate = ref('')
const selectedDatePreset = ref('')

// 记录列表
const recordList = ref([])
const statistics = ref({})
const currentRecord = ref({})
const selectedPaymentMethod = ref('wechat')

// 日期预设
const datePresets = [
  { label: '今天', value: 'today' },
  { label: '昨天', value: 'yesterday' },
  { label: '最近7天', value: '7days' },
  { label: '最近30天', value: '30days' },
  { label: '本月', value: 'month' },
  { label: '自定义', value: 'custom' }
]

// 支付方式
const paymentMethods = [
  { label: '微信支付', value: 'wechat', icon: 'weixin' },
  { label: '支付宝', value: 'alipay', icon: 'wallet' },
  { label: '余额支付', value: 'balance', icon: 'wallet' }
]

// 计算属性
const dateRangeText = computed(() => {
  if (selectedDatePreset.value === 'custom') {
    return `${customStartDate.value} 至 ${customEndDate.value}`
  }
  const preset = datePresets.find(p => p.value === selectedDatePreset.value)
  return preset ? preset.label : '全部时间'
})

const sortText = computed(() => {
  switch (sortType.value) {
    case 'time': return '时间排序'
    case 'amount': return '金额排序'
    case 'power': return '电量排序'
    default: return '时间排序'
  }
})

// 获取充电记录列表
const getRecordList = async () => {
  try {
    loadMoreStatus.value = 'loading'
    
    // 模拟API调用
    const params = {
      tab: activeTab.value,
      sort: sortType.value,
      datePreset: selectedDatePreset.value,
      startDate: customStartDate.value,
      endDate: customEndDate.value,
      page: 1,
      size: 20
    }
    
    // 这里应该调用真实的API
    const mockData = [
      {
        id: 1,
        pileNo: 'CP001',
        pileType: 1,
        pileTypeName: '慢充',
        status: 2,
        statusName: '已完成',
        licensePlate: '京A12345',
        startTime: '2024-01-01 10:00:00',
        endTime: '2024-01-01 12:00:00',
        duration: 7200, // 秒
        chargedPower: 14.5,
        chargedAmount: 11.6,
        paymentStatus: 0
      },
      {
        id: 2,
        pileNo: 'CP002',
        pileType: 2,
        pileTypeName: '快充',
        status: 1,
        statusName: '充电中',
        licensePlate: '京B67890',
        startTime: '2024-01-01 14:00:00',
        endTime: null,
        duration: null,
        chargedPower: 8.2,
        chargedAmount: 9.84,
        paymentStatus: 0
      }
    ]
    
    recordList.value = mockData
    loadMoreStatus.value = 'noMore'
  } catch (error) {
    console.error('获取充电记录失败:', error)
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    })
    loadMoreStatus.value = 'more'
  }
}

// 获取统计信息
const getStatistics = async () => {
  try {
    // 这里应该调用真实的API
    statistics.value = {
      totalCount: 25,
      totalAmount: 156.8,
      totalPower: 89.5,
      avgDuration: 2.3
    }
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

// 切换标签
const switchTab = (tab) => {
  activeTab.value = tab
  getRecordList()
}

// 排序
const handleSort = () => {
  const sortOptions = [
    { label: '时间排序', value: 'time' },
    { label: '金额排序', value: 'amount' },
    { label: '电量排序', value: 'power' }
  ]
  
  uni.showActionSheet({
    itemList: sortOptions.map(item => item.label),
    success: (res) => {
      sortType.value = sortOptions[res.tapIndex].value
      getRecordList()
    }
  })
}

// 选择日期预设
const selectDatePreset = (preset) => {
  selectedDatePreset.value = preset.value
  if (preset.value !== 'custom') {
    confirmDateFilter()
  }
}

// 开始日期改变
const onStartDateChange = (e) => {
  customStartDate.value = e.detail.value
}

// 结束日期改变
const onEndDateChange = (e) => {
  customEndDate.value = e.detail.value
}

// 确认日期筛选
const confirmDateFilter = () => {
  showDateFilter.value = false
  getRecordList()
}

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 1: return 'status-charging'
    case 2: return 'status-completed'
    case 3: return 'status-cancelled'
    default: return 'status-completed'
  }
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  return timeStr.replace('T', ' ').substring(0, 16)
}

// 格式化时长
const formatDuration = (seconds) => {
  if (!seconds) return ''
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  return `${hours}小时${minutes}分钟`
}

// 点击记录项
const handleItemClick = (item) => {
  uni.navigateTo({
    url: `/pages/parking/charging-record-detail?id=${item.id}`
  })
}

// 停止充电
const handleStopCharging = async (item) => {
  try {
    const res = await uni.showModal({
      title: '提示',
      content: '确定要停止充电吗？'
    })
    
    if (res.confirm) {
      // 这里应该调用停止充电API
      uni.showToast({
        title: '停止充电成功',
        icon: 'success'
      })
      getRecordList()
      getStatistics()
    }
  } catch (error) {
    console.error('停止充电失败:', error)
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  }
}

// 支付
const handlePayment = (item) => {
  currentRecord.value = item
  selectedPaymentMethod.value = 'wechat'
  showPaymentPopup.value = true
}

// 选择支付方式
const selectPaymentMethod = (method) => {
  selectedPaymentMethod.value = method.value
}

// 确认支付
const confirmPayment = async () => {
  try {
    // 这里应该调用支付API
    console.log('支付方式:', selectedPaymentMethod.value)
    console.log('支付金额:', currentRecord.value.chargedAmount)
    
    uni.showToast({
      title: '支付成功',
      icon: 'success'
    })
    
    showPaymentPopup.value = false
    getRecordList()
    getStatistics()
  } catch (error) {
    console.error('支付失败:', error)
    uni.showToast({
      title: '支付失败',
      icon: 'none'
    })
  }
}

// 查看详情
const handleDetail = (item) => {
  uni.navigateTo({
    url: `/pages/parking/charging-record-detail?id=${item.id}`
  })
}

// 初始化
onMounted(() => {
  getRecordList()
  getStatistics()
})
</script>

<style scoped>
.charging-record-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.statistics-section {
  background-color: #fff;
  padding: 30rpx 20rpx;
  margin-bottom: 20rpx;
}

.statistics-card {
  display: flex;
  justify-content: space-between;
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-value {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #007aff;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
}

.filter-section {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.filter-tabs {
  display: flex;
  margin-bottom: 20rpx;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 20rpx;
  font-size: 28rpx;
  color: #666;
  border-bottom: 4rpx solid transparent;
}

.tab-item.active {
  color: #007aff;
  border-bottom-color: #007aff;
}

.filter-actions {
  display: flex;
  gap: 20rpx;
}

.filter-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  background-color: #f8f8f8;
  border-radius: 10rpx;
  font-size: 26rpx;
  color: #666;
}

.filter-btn text {
  margin-left: 10rpx;
}

.record-list {
  padding: 20rpx;
}

.record-item {
  background-color: #fff;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.pile-info {
  display: flex;
  align-items: center;
}

.pile-no {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-right: 20rpx;
}

.pile-type {
  font-size: 24rpx;
  color: #666;
  background-color: #f0f0f0;
  padding: 8rpx 16rpx;
  border-radius: 12rpx;
}

.status-tag {
  font-size: 24rpx;
  padding: 8rpx 16rpx;
  border-radius: 12rpx;
}

.status-charging {
  background-color: #fff7e6;
  color: #fa8c16;
}

.status-completed {
  background-color: #e8f5e8;
  color: #52c41a;
}

.status-cancelled {
  background-color: #fff2f0;
  color: #ff4d4f;
}

.record-content {
  margin-bottom: 20rpx;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15rpx;
  font-size: 28rpx;
}

.label {
  color: #666;
}

.value {
  color: #333;
}

.value.price {
  color: #ff4d4f;
  font-weight: bold;
}

.record-footer {
  border-top: 1rpx solid #f0f0f0;
  padding-top: 20rpx;
}

.actions {
  display: flex;
  gap: 20rpx;
}

.action-btn {
  flex: 1;
  font-size: 24rpx;
  padding: 12rpx 24rpx;
  border-radius: 20rpx;
  border: none;
}

.action-btn.primary {
  background-color: #007aff;
  color: #fff;
}

.action-btn.info {
  background-color: #ff9500;
  color: #fff;
}

.action-btn.default {
  background-color: #f0f0f0;
  color: #666;
}

.popup-content {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 80vh;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
  font-size: 32rpx;
  font-weight: bold;
}

.popup-body {
  padding: 30rpx;
}

.date-presets {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.preset-item {
  flex: 1;
  min-width: 150rpx;
  text-align: center;
  padding: 20rpx;
  background-color: #f8f8f8;
  border-radius: 10rpx;
  font-size: 28rpx;
  color: #666;
}

.custom-date {
  margin-bottom: 30rpx;
}

.date-input {
  margin-bottom: 20rpx;
}

.date-input .label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.picker {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
}

.popup-actions {
  display: flex;
  gap: 20rpx;
}

.btn {
  flex: 1;
  height: 80rpx;
  border-radius: 10rpx;
  font-size: 30rpx;
  border: none;
}

.btn.cancel {
  background-color: #f0f0f0;
  color: #666;
}

.btn.confirm {
  background-color: #007aff;
  color: #fff;
}

.payment-popup {
  background-color: #fff;
  border-radius: 20rpx;
  width: 600rpx;
  padding: 40rpx;
}

.popup-title {
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 40rpx;
}

.payment-info {
  margin-bottom: 40rpx;
}

.payment-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
  font-size: 28rpx;
}

.payment-item.total {
  border-top: 1rpx solid #eee;
  padding-top: 20rpx;
  font-weight: bold;
}

.payment-methods {
  margin-bottom: 40rpx;
}

.method-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.method-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border: 1rpx solid #eee;
  border-radius: 10rpx;
  margin-bottom: 15rpx;
}

.method-info {
  display: flex;
  align-items: center;
  font-size: 28rpx;
}

.method-info text {
  margin-left: 15rpx;
}
</style> 